package com.apex.oauth.security.service.impl;

import com.apex.common.util.JsonUtils;
import com.apex.oauth.security.domian.UserLoginDomain;
import com.apex.oauth.security.entity.SecurityUser;
import com.apex.oauth.security.service.UserInformationService;
import com.apex.security.api.entity.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

/**
 * 用户登录处理
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-4-3
 */
public class UserInformationServiceImpl implements UserInformationService,UserDetailsService {

    @Autowired
    private UserLoginDomain domain;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser user = findByLoginId(username);
        if (user == null) {
            throw new UsernameNotFoundException("UserName " + username + " not found");
        }
        SecurityUser securityUser=new SecurityUser(user);
        return securityUser;
    }

    @Override
    public TUser findByLoginId(String userId) {
        String code=domain.findByUserId(userId);
        if(!StringUtils.isEmpty(code)){
            TUser tUser= JsonUtils.toObject(code,TUser.class);
            return tUser;
        }
        return null;
    }
}
